package dao

import (
	"context"
	"fmt"
	jsoniter "github.com/json-iterator/go"
	"ldaccount/internal/conf"
	"ldaccount/pkg/db/pgex"
	"ldaccount/pkg/db/redisex"
	"ldaccount/pkg/mq"
)

var json = jsoniter.ConfigCompatibleWithStandardLibrary

type Dao struct {
	cfg   *conf.Config
	db    *pgex.SqlEx
	cache *redisex.RedisEX
	nsq   *mq.NsqProducer
}

var dao *Dao

// InitDao 初始化 Dao
func InitDao(cfg *conf.Config, pgsql *pgex.SqlEx, redis *redisex.RedisEX, nsq *mq.NsqProducer) {
	dao = &Dao{
		db:    pgsql,
		cache: redis,
		nsq:   nsq,
		cfg:   cfg,
	}
}

// Transaction 开启事务胶囊
func Transaction(ctx context.Context, capFunc func(ctx context.Context) (interface{}, error)) (interface{}, error) {
	return dao.db.StartCapsule(ctx, true, capFunc)
}

func isNil(err error) bool {
	return err.Error() == "redis: nil"
}

func (d *Dao) BuildCacheKey(key string, params ...string) string {
	key = fmt.Sprintf("bilin-account:%s", key)
	for _, p := range params {
		key += fmt.Sprintf(":%s", p)
	}
	return key
}
